package com.zenithmind.gateway.route;

import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder.Builder;
import org.springframework.cloud.gateway.route.builder.GatewayFilterSpec;
import org.springframework.stereotype.Component;
import lombok.extern.slf4j.Slf4j;

/**
 * 工具类和文档相关服务路由配置器
 * 专门负责任务服务、API测试服务、文档服务的路由配置
 * 遵循单一职责原则：只负责工具类和文档相关的路由配置
 */
@Slf4j
@Component
public class ToolsAndDocumentationRouteConfigurer implements RouteConfigurer {

    @Override
    public void configureRoutes(Builder routes) {
        log.info("配置工具类和文档相关服务路由...");
        
        // 任务服务路由 - 任务、日程、提醒
        routes.route("task-service-route", r -> r
            .path("/api/zenithMind/task/**",
                 "/api/zenithMind/schedule/**",
                 "/api/zenithMind/reminder/**",
                 "/api/zenithMind/api/v1/tasks/**", 
                 "/api/zenithMind/api/v1/task-attachment/**", 
                 "/api/zenithMind/api/v1/task-assignment/**")
            // 仅为API v1路径应用stripPrefix过滤器
            .filters(f -> pathFilterForApiV1(f, "/api/zenithMind/api/v1/"))
            .uri("lb://task-service"));
            
        // API测试服务路由
        routes.route("api-test-service-route", r -> r
            .path("/api/test/**", 
                 "/api/services/**")
            .uri("lb://api-test-service"));
            
        // Swagger UI 路由
        routes.route("swagger-ui-route", r -> r
            .path("/swagger-ui/**", 
                 "/v3/api-docs/**", 
                 "/doc.html", 
                 "/webjars/**")
            .uri("lb://gateway-service"));
            
        // Knife4j 路由
        routes.route("knife4j-route", r -> r
            .path("/knife4j/**", 
                 "/knife4j-ui/**", 
                 "/knife4j.html")
            .uri("lb://gateway-service"));
            
        // Favicon 路由
        routes.route("favicon-route", r -> r
            .path("/favicon.ico")
            .uri("forward:/favicon.ico"));
        
        // 健康检查和监控路由
        routes.route("actuator-route", r -> r
            .path("/actuator/**", 
                 "/health", 
                 "/info")
            .uri("lb://gateway-service"));
    }

    @Override
    public String getConfigureName() {
        return "ToolsAndDocumentationRouteConfigurer";
    }

    @Override
    public int getOrder() {
        return 6; // 工具类和文档路由优先级较低
    }
    
    /**
     * 路径过滤器工具方法 - 专用于/api/zenithMind/api/v1/前缀的路径
     * 如果路径以指定前缀开头，则移除前缀
     */
    private GatewayFilterSpec pathFilterForApiV1(GatewayFilterSpec f, String prefixPattern) {
        return f.rewritePath("/api/zenithMind/api/v1/(?<segment>.*)", "/api/zenithMind/${segment}");
    }
}
